package com.chd.driversystem.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anderson.dashboardview.view.DashboardView;
import com.chd.driversystem.R;
import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.domain.DrivingRecord;
import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.Oil;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.service.HttpService;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.Constants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class ManagerActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "ManagerActivity";

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.btn_offline)
    Button btn_back;

    @BindView(R.id.iv_avator)
    CircleImageView civAvator;

    @BindView(R.id.tv_username)
    TextView tvUsername;

    @BindView(R.id.tv_userjob)
    TextView tvJob;

    @BindView(R.id.tv_usercode)
    TextView tvCode;

    @BindView(R.id.tv_userphone)
    TextView tvPhone;

    @BindView(R.id.tv_useremail)
    TextView tvEmail;

    @BindView(R.id.tv_count)
    TextView tvCount;

    @BindView(R.id.tv_totaldistance)
    TextView tvTotalDistance;

    @BindView(R.id.ibtn_ranking)
    ImageButton ibRanking;

    @BindView(R.id.lc_allscore)
    LineChart lcAllscore;

    @BindView(R.id.pc_fineproportion)
    PieChart pcFineProportion;

    @BindView(R.id.dv_totaloilofmonth)
    DashboardView dvTotalOil;

    private double totalfuel = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        toolbar.setTitle("管理者");
        toolbar.setContentInsetStartWithNavigation(430);
        setSupportActionBar(toolbar);

        //后台服务参数
        params = new HashMap<>();
        params.put(Constants.EXTRA_PARAM1, Evaluation.DAY_EVALUATION);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.home);
        }
        viewInit();
        LogUtil.d(TAG, "User = " + MyApplication.getUser().toString());
    }

    private void viewInit() {
        Log.d(TAG, "viewInit() called start");

        //仪表盘绘制监听器
        ViewTreeObserver vto = dvTotalOil.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                        dvTotalOil.getLayoutParams();
                layoutParams.height = dvTotalOil.getWidth();
                dvTotalOil.setLayoutParams(layoutParams);
                dvTotalOil.setPercent((int) (totalfuel / 30));
            }
        });

        ibRanking.setOnClickListener(this);

        initCharts();

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Constants.ACTION_LOGOUT);
                sendBroadcast(intent);
            }
        });

        User user = MyApplication.getUser();
        tvUsername.setText(user.getName());
        if (user.getIsManager()) {
            tvJob.setText("管理员");
        } else {
            tvJob.setText("司机");
        }
        tvCode.setText(user.getCode());
        if (!TextUtils.isEmpty(user.getPhoneNum())) {
            tvPhone.setText(user.getPhoneNum());
        } else {
            tvPhone.setText("未设置");
        }
        if (!TextUtils.isEmpty(user.getEmail())) {
            tvEmail.setText(user.getEmail());
        } else {
            tvEmail.setText("未设置");
        }

        Log.d(TAG, "viewInit() called end");

    }

    private void initCharts() {
        Log.d(TAG, "initCharts() called start");
        /**************************折线图********************************/
        //折线图--分数走势图
        lcAllscore.setPinchZoom(true);
        lcAllscore.setScaleYEnabled(false);
        lcAllscore.setLogEnabled(false);
        lcAllscore.setDrawGridBackground(true);
        lcAllscore.setGridBackgroundColor(Color.TRANSPARENT);
        lcAllscore.setDrawBorders(true);
        lcAllscore.setBorderColor(Color.WHITE);
        lcAllscore.setHighlightPerDragEnabled(true);
        lcAllscore.setHighlightPerTapEnabled(true);
        Description des = new Description();
        des.setText("队内成员平均驾驶能力走势图");
        lcAllscore.setDescription(des);
        lcAllscore.animateX(2500);

        /**************************饼图********************************/
        //饼图--优良比例
        pcFineProportion.setUsePercentValues(true);
        pcFineProportion.getDescription().setEnabled(false);
        pcFineProportion.setExtraOffsets(5, 10, 5, 5);

        pcFineProportion.setDragDecelerationFrictionCoef(0.95f);

        pcFineProportion.setCenterText("优良比");

        pcFineProportion.setDrawHoleEnabled(true);
        pcFineProportion.setHoleColor(Color.WHITE);

        pcFineProportion.setTransparentCircleColor(Color.WHITE);
        pcFineProportion.setTransparentCircleAlpha(110);

        pcFineProportion.setHoleRadius(40f);
        pcFineProportion.setTransparentCircleRadius(43f);

        pcFineProportion.setDrawCenterText(true);

        pcFineProportion.setRotationAngle(270);
        // enable rotation of the chart by touch
        pcFineProportion.setRotationEnabled(true);
        pcFineProportion.setHighlightPerTapEnabled(true);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        // add a selection listener
        pcFineProportion.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }

            @Override
            public void onNothingSelected() {

            }
        });

        pcFineProportion.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);

        Legend l = pcFineProportion.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(20f);

        // entry label styling
        pcFineProportion.setEntryLabelColor(Color.TRANSPARENT);
        pcFineProportion.setEntryLabelTextSize(12f);


        /**************************仪表盘********************************/
        //dvTotalOil.setLayoutParams(new RelativeLayout.LayoutParams(100,100));
        //dvTotalOil.setPercent(80);//核心方法，percent = 0~100
        dvTotalOil.setText("月总耗油");
        dvTotalOil.setTextSize(25);
        dvTotalOil.setTextColor(Color.BLACK);
        dvTotalOil.setUnit("L");
//        TimeInterpolator interpolator = new TimeInterpolator() {
//            @Override
//            public float getInterpolation(float input) {
//                return 0;
//            }
//        };
//        dvTotalOil.setInterpolator(interpolator);//设置动画插值器，从而达到不同的动画效果
        dvTotalOil.setStartColor(Color.GREEN);
        dvTotalOil.setEndColor(Color.RED);//如果设置了起始颜色和结束颜色，进度条会变成渐变色
        dvTotalOil.setStartNum(0);
        dvTotalOil.setMaxNum(3000);


        Log.d(TAG, "initCharts() called end");
    }

    private void refreshPieChartDatas() {
        LogUtil.d(TAG, "refreshPieChart() called");

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        long veryBadCount = BeanServer.getInstance().getCountEvaByRange(0, 60);
        long badCount = BeanServer.getInstance().getCountEvaByRange(60, 70);
        long commonCount = BeanServer.getInstance().getCountEvaByRange(70, 80);
        long goodCount = BeanServer.getInstance().getCountEvaByRange(80, 90);
        long veryGoodCount = BeanServer.getInstance().getCountEvaByRange(90, 100);

        LogUtil.d(TAG, "refreshPieChartDatas() called count1=" + veryBadCount +
                "; count2=" + badCount + "; count3=" + commonCount + "; count4=" + goodCount + "; count5=" + veryGoodCount);
        if (veryBadCount+badCount+commonCount+goodCount+veryGoodCount>0) {
            entries.add(new PieEntry(veryGoodCount, "非常好"));
            entries.add(new PieEntry(goodCount, "好"));
            entries.add(new PieEntry(commonCount, "一般"));
            entries.add(new PieEntry(badCount, "不好"));
            entries.add(new PieEntry(veryBadCount, "非常不好"));

            PieData data = pcFineProportion.getData();
            PieDataSet dataSet;
            if (data != null && data.getDataSetCount() > 0) {
                dataSet = (PieDataSet) data.getDataSet();
                dataSet.setValues(entries);
            } else {
                dataSet = new PieDataSet(entries, "综合能力比例图");
                dataSet.setDrawIcons(false);
                dataSet.setSliceSpace(3f);
                dataSet.setIconsOffset(new MPPointF(0, 40));
                dataSet.setSelectionShift(5f);
                // add a lot of colors
                ArrayList<Integer> colors = new ArrayList<Integer>();
                for (int c : ColorTemplate.VORDIPLOM_COLORS)
                    colors.add(c);
                for (int c : ColorTemplate.JOYFUL_COLORS)
                    colors.add(c);
                for (int c : ColorTemplate.COLORFUL_COLORS)
                    colors.add(c);
                for (int c : ColorTemplate.LIBERTY_COLORS)
                    colors.add(c);
                for (int c : ColorTemplate.PASTEL_COLORS)
                    colors.add(c);
                colors.add(ColorTemplate.getHoloBlue());
                dataSet.setColors(colors);
                //dataSet.setSelectionShift(0f);
                data = new PieData(dataSet);
                data.setValueFormatter(new PercentFormatter());
                data.setValueTextSize(11f);
                data.setValueTextColor(Color.BLACK);

                pcFineProportion.setData(data);
                pcFineProportion.notifyDataSetChanged();
            }
        }
    }


    private void refreshLineChartDatas(int type) {
        LogUtil.d(TAG, "refreshLineCharts() called with: type = [" + type + "]");
        List<Evaluation> evaluations = BeanServer.getInstance().getEvaluationsByType
                (MyApplication.getUser().getId(), type);
        List<Entry> tscore = new ArrayList<>();
        List<Entry> stabilities = new ArrayList<>();
        List<Entry> opSpeces = new ArrayList<>();
        List<Entry> vehHealths = new ArrayList<>();
        List<Entry> drExpericens = new ArrayList<>();
        List<Entry> esDriving = new ArrayList<>();
        if (evaluations.size() > 0) {
            long x = 0;
            for (Evaluation evaluation : evaluations) {
                x++;
                tscore.add(new Entry(x, evaluation.getTScore()));
                stabilities.add(new Entry(x, evaluation.getStability()));
                opSpeces.add(new Entry(x, evaluation.getOpSpec()));
                vehHealths.add(new Entry(x, evaluation.getVehHealth()));
                drExpericens.add(new Entry(x, evaluation.getDrExpericen()));
                esDriving.add(new Entry(x, evaluation.getEsDriving()));
            }
            LineData lineData = lcAllscore.getData();
            LineDataSet dsTscore;
//            LineDataSet dsStabilities;
//            LineDataSet dsOpSpeces;
//            LineDataSet dsVehHealths;
//            LineDataSet dsDrExpericens;
            LineDataSet dsEsDriving;
            if (lineData != null &&
                    lineData.getDataSetCount() > 0) {
                dsTscore = (LineDataSet) lineData.getDataSetByIndex(0);
                dsTscore.setValues(tscore);
//                dsStabilities = (LineDataSet) lineData.getDataSetByIndex(1);
//                dsStabilities.setValues(stabilities);
//
//                dsOpSpeces = (LineDataSet) lineData.getDataSetByIndex(2);
//                dsOpSpeces.setValues(opSpeces);
//
//                dsVehHealths = (LineDataSet) lineData.getDataSetByIndex(3);
//                dsVehHealths.setValues(vehHealths);
//
//                dsDrExpericens = (LineDataSet) lineData.getDataSetByIndex(4);
//                dsDrExpericens.setValues(drExpericens);
                dsEsDriving = (LineDataSet) lineData.getDataSetByIndex(1);
                dsEsDriving.setValues(esDriving);
            } else {
                dsTscore = new LineDataSet(tscore, "综合");
                dsTscore.setColor(Color.GREEN);
                dsTscore.setValueTextColor(Color.rgb(73, 255, 0));
                dsTscore.setDrawCircles(false);
                dsTscore.setCubicIntensity(0.6f);
                dsTscore.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//                dsStabilities = new LineDataSet(stabilities, "稳定性");
//                dsStabilities.setColor(Color.MAGENTA);
//                dsStabilities.setValueTextColor(Color.rgb(73, 255, 0));
//                dsStabilities.setDrawCircles(false);
//                dsStabilities.setCubicIntensity(0.6f);
//                dsStabilities.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsOpSpeces = new LineDataSet(opSpeces, "操作");
//                dsOpSpeces.setColor(Color.YELLOW);
//                dsOpSpeces.setValueTextColor(Color.rgb(73, 255, 0));
//                dsOpSpeces.setDrawCircles(false);
//                dsOpSpeces.setCubicIntensity(0.6f);
//                dsOpSpeces.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsVehHealths = new LineDataSet(vehHealths, "车辆健康");
//                dsVehHealths.setColor(Color.GRAY);
//                dsVehHealths.setValueTextColor(Color.rgb(73, 255, 0));
//                dsVehHealths.setDrawCircles(false);
//                dsVehHealths.setCubicIntensity(0.6f);
//                dsVehHealths.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsDrExpericens = new LineDataSet(drExpericens, "驾驶经验");
//                dsDrExpericens.setColor(Color.CYAN);
//                dsDrExpericens.setValueTextColor(Color.rgb(73, 255, 0));
//                dsDrExpericens.setDrawCircles(false);
//                dsDrExpericens.setCubicIntensity(0.6f);
//                dsDrExpericens.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
                dsEsDriving = new LineDataSet(esDriving, "经济驾驶");
                dsEsDriving.setColor(Color.BLUE);
                dsEsDriving.setValueTextColor(Color.rgb(73, 255, 0));
                dsEsDriving.setDrawCircles(false);
                dsEsDriving.setCubicIntensity(0.6f);
                dsEsDriving.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
                List<ILineDataSet> dataSets = new ArrayList<>();
                dataSets.add(dsTscore);
//                dataSets.add(dsStabilities);
//                dataSets.add(dsOpSpeces);
//                dataSets.add(dsVehHealths);
//                dataSets.add(dsDrExpericens);
                dataSets.add(dsEsDriving);
                lineData = new LineData(dataSets);
                lcAllscore.setData(lineData);
                lcAllscore.notifyDataSetChanged();
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_driver:

                break;
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            default:
                break;
        }
        return true;
    }


    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ManagerActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_ranking:
                RankingActivity.actionStart(this);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpService.startServiceUserList(
                MyApplication.getContext(),
                MyApplication.getUser().getId()
        );
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //初始化图表
        EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_EVALUATION,
                HttpConstants.RESULT_OK, null, 1, 0));
        EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND,
                HttpConstants.ACTION_OILBYDAY,
                HttpConstants.RESULT_OK,
                null,
                1, 0));
        EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND,
                HttpConstants.ACTION_USERLIST,
                HttpConstants.RESULT_OK,
                null,
                1, 0));
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCharts(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.MAIN) {
            Log.d(TAG, "refreshCharts() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATION:
                    lcAllscore.invalidate();
                    pcFineProportion.invalidate();
                    break;
                case HttpConstants.ACTION_OILBYDAY:
                case HttpConstants.ACTION_OILBYMONTH: {
                    totalfuel = (double) netMsg.getObj();
                    dvTotalOil.setPercent((int) (totalfuel / 30));//核心方法，percent
                    // = 0~100
                    break;
                }
                case HttpConstants.ACTION_USERLIST: {
                    Long count = (Long) netMsg.getObj();
                    tvCount.setText(count.toString());
                    break;
                }
                case HttpConstants.ACTION_DRIVINGRECORD: {
                    Integer distance = (Integer) netMsg.getObj();
                    tvTotalDistance.setText(distance.toString());
                    break;
                }
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void receiverNetMsg(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.BACKGROUND) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATION:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            refreshLineChartDatas(Evaluation.DAY_EVALUATION);
                            refreshPieChartDatas();
                            netMsg.setType(NetMsg.MAIN);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                case HttpConstants.ACTION_OILBYDAY:
                case HttpConstants.ACTION_OILBYMONTH: {
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getId() > 0) {
                            Oil oil = BeanServer.getInstance().getOilLastByUserId(MyApplication
                                    .getUser().getId());
                            if (oil != null) {
                                netMsg.setObj(oil.getTotalFuel());
                            }
                            netMsg.setType(NetMsg.MAIN);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                }
                case HttpConstants.ACTION_USERLIST: {
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        netMsg.setObj(BeanServer.getInstance().getUserSize());
                        netMsg.setType(NetMsg.MAIN);
                    } else {
                        //提示错误信息
                        LogUtil.d(TAG, "receiverNetMsg: " + netMsg.getERR_MSG());
                    }

                    break;
                }
                case HttpConstants.ACTION_DRIVINGRECORD: {
                    LogUtil.d(TAG, "receiverNetMsg() called with:" + HttpConstants.ACTION_DRIVINGRECORD);
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        DrivingRecord drivingRecord = BeanServer.getInstance()
                                .getLastDrivingRecordByUserId(MyApplication.getUser().getId());
                        netMsg.setObj(drivingRecord.getTDistance());
                        netMsg.setType(NetMsg.MAIN);
                    } else {
                        //提示错误信息
                        LogUtil.d(TAG, "receiverNetMsg: " + netMsg.getERR_MSG());
                    }
                    break;
                }

                default:
                    break;
            }
        }
    }
}
